package com.justalk.testapplication

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.ByteArrayOutputStream
import java.nio.charset.Charset


class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"

    var textView01: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 初始化UI控件
        initUI()
        // 加载数据
        val textViewStr: String = this!!.loadFromAssetsFile("baike_textdemo.txt")!!

        // 数据显示

        // 数据显示
        textView01!!.text = textViewStr
    }

    private fun initUI() {
        textView01 = findViewById<BaikeTextView>(R.id.textView01)

        (textView01 as BaikeTextView).setMovementMethod(ScrollingMovementMethod.getInstance());
        (textView01 as BaikeTextView).setOnTouchListener(OnTouchListener(fun(
            v: View,
            event: MotionEvent
        ): Boolean {
            if (event.action == MotionEvent.ACTION_DOWN) {
                v.parent.requestDisallowInterceptTouchEvent(true)
            }
            if (event.action == MotionEvent.ACTION_MOVE) {
                v.parent.requestDisallowInterceptTouchEvent(true)
            }
            if (event.action == MotionEvent.ACTION_UP) {
                v.parent.requestDisallowInterceptTouchEvent(false)
            }
            if (event.action == MotionEvent.ACTION_CANCEL) {

            }
            return false
        }))
        (textView01 as BaikeTextView).setOnClickListener(View.OnClickListener { Toast.makeText(this,"ok,bucuo",Toast.LENGTH_SHORT ).show() })
    }

    private fun loadFromAssetsFile(fname: String): String? {
        var result: String? = null
        try {
            val `in` = this.resources.assets.open(fname)
            var ch = 0
            val baos = ByteArrayOutputStream()
            while (`in`.read().also { ch = it } != -1) {
                baos.write(ch)
            }
            val buff = baos.toByteArray()
            baos.close()
            `in`.close()
            result = String(buff, Charset.defaultCharset())
            result = result.replace("\\r\\n".toRegex(), "\n")
        } catch (e: Exception) {
            Log.i(TAG, "the local file did not find")
            e.printStackTrace()
        }
        return result
    }


}